package com.bsb.biz.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bsb.base.common.config.Global;
import com.bsb.base.common.util.BeanUtils;
import com.bsb.base.common.util.DateUtils;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.BsbFirm;
import com.bsb.base.model.BsbFirmExample;
import com.bsb.base.model.Firm;
import com.bsb.base.model.SysOrganization;
import com.bsb.base.model.SysOrganizationExample;
import com.bsb.base.model.SysOrganizationExample.Criteria;
import com.bsb.biz.service.BsbFirmService;
import com.bsb.biz.service.BsbUserService;
import com.bsb.biz.service.SysOrganizationService;
import com.bsb.biz.service.ValidateCodeService;

@Controller
@RequestMapping("/bsbFirm")
public class BsbFirmController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbFirm/list.do";
	
	@Resource
	private BsbFirmService bsbFirmService;
	@Resource
	private BsbUserService bsbUserService;
	@Resource
	private ValidateCodeService validateCodeService;
	@Resource
	private SysOrganizationService sysOrganizationService;
	
	@RequiresPermissions("bsbFirm:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,@RequestParam Map<String, Object> params,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		String name = (String) params.get("name");
		String phone = (String) params.get("phone");
		String rapidLimit = (String) params.get("rapidLimit");
		String start = (String) params.get("start");
		Date startDate = DateUtils.parseDate(start);
		String end = (String) params.get("end");
		Date endDate = DateUtils.parseDate(end);
		BsbFirmExample bsbFirmExample = new BsbFirmExample();
		com.bsb.base.model.BsbFirmExample.Criteria criteria = bsbFirmExample.createCriteria();
		criteria.andDelFlagEqualTo(Global.SHOW);
		if(StringUtils.isNotEmpty(name)){
			criteria.andNameLike("%"+name+"%");
		}
		if(StringUtils.isNotEmpty(phone)){
			criteria.andPhoneLike("%"+phone+"%");
		}
		if(StringUtils.isNotEmpty(rapidLimit)){
			criteria.andRapidLimitEqualTo(rapidLimit);
		}
		if(null != startDate){
			criteria.andCredateDateGreaterThanOrEqualTo(startDate);
		}
		if(null != endDate){
			endDate = DateUtils.addDays(endDate, 1);
			criteria.andCredateDateLessThanOrEqualTo(endDate);
		}
		int totalCount = bsbFirmService.countBsbFirm(bsbFirmExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbFirmExample.setPageIndex((pageNum - 1) * pageSize);
		bsbFirmExample.setPageSize(pageSize);
		bsbFirmExample.setOrderByClause("credateDate DESC");
		List<BsbFirm> bsbFirms = bsbFirmService.getPageBsbFirm(bsbFirmExample);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("name", name);
		model.addAttribute("phone", phone);
		model.addAttribute("rapidLimit", rapidLimit);
		model.addAttribute("start", start);
		model.addAttribute("end", end);
		model.addAttribute("bsbFirms", bsbFirms);
		return "/BsbFirm/list";
	}
	/**
	 * 生成会员卡时选择事务所 modal
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequiresPermissions("bsbFirm:view")
	@RequestMapping(value="/selectlist",method = RequestMethod.GET)
	public String selectlist(
			Model model,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbFirmExample bsbFirmExample = new BsbFirmExample();
		int totalCount = bsbFirmService.countBsbFirm(bsbFirmExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbFirmExample.setPageIndex((pageNum - 1) * pageSize);
		bsbFirmExample.setPageSize(pageSize);
		List<BsbFirm> bsbFirms = bsbFirmService.getPageBsbFirm(bsbFirmExample);
		
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("bsbFirms", bsbFirms);
		return "/BsbCardBatch/selectFirm";
	}
	
	@RequiresPermissions("bsbFirm:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "/BsbFirm/add";
	}

	/*@RequiresPermissions("bsbFirm:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Object add(Model model,String phone,String pwd,String code,
			@ModelAttribute("bsbFirm") BsbFirm bsbFirm) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtils.isEmpty(code)){
			map.put("status", false);
			map.put("msg", "验证码不能为空");
			return map;
		}
		if(!StringUtils.isMobile(phone)){
			map.put("status", false);
			map.put("msg", "手机号格式不正确");
			return map;
		}
		if(StringUtils.isEmpty(pwd)){
			map.put("status", false);
			map.put("msg", "初始密码不能为空");
			return map;
		}
		if(!validateCodeService.checkSmsCode(code)){
			map.put("status", false);
			map.put("msg", "验证码错误");
			return map;
		}
		BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
		if(null != userByPhone){
			map.put("status", false);
			map.put("msg", "该手机号码已存在");
			return map;
		}
		bsbFirm.setCredateDate(new Date());
		BsbUser user = new BsbUser();
		user.setUuid(IdGen.uuid());
		user.setPhone(phone);
		user.setPwd(Md5Util.Md5(pwd));
		user.setRegistTime(new Date());
		user.setRole("2");
		try {
			bsbFirmService.addFirm(bsbFirm,user);
			map.put("status", true);
			map.put("msg", "添加成功");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙，请联系管理员");
			return map;
		}
	}*/
	
	@RequiresPermissions("bsbFirm:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Object add(Model model,@ModelAttribute("bsbFirm") BsbFirm bsbFirm) {
		Map<String,Object> map = new HashMap<String,Object>();
		bsbFirm.setCredateDate(new Date());
		SysOrganization org = new SysOrganization();
		org.setName(bsbFirm.getName());
		org.setParent_id(12L);
		try {
			bsbFirmService.addFirmAndDept(bsbFirm,org);
			map.put("status", true);
			map.put("msg", "添加成功");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙，请联系管理员");
			return map;
		}
	}
	
	@RequiresPermissions("bsbFirm:delete")
	@RequestMapping(value = "/{account}/delete", method = RequestMethod.GET)
	public String del(Model model,HttpServletRequest request,
			@PathVariable("account") Long account) {
		String queryString = request.getQueryString();
		bsbFirmService.delBsbFirm(account);
		return redirect+ "?" +queryString;
	}
	
	@RequiresPermissions("bsbFirm:update")
	@RequestMapping(value = "/{account}/update", method = RequestMethod.GET)
	public String toEdit(Model model,
			HttpServletRequest request,
			@PathVariable("account") Integer account) {
		BsbFirm bsbFirm = bsbFirmService.getBsbFirmByAccount(account);
		String phone = bsbFirmService.getPhoneByFirmId(account);
		Firm firm = new Firm();
		BeanUtils.copyProperties(firm, bsbFirm);
		if(StringUtils.isNotEmpty(phone)){
			firm.setPhone(phone);
		}
		model.addAttribute("bsbFirm", firm);
		String queryString = request.getQueryString();
		model.addAttribute("queryString", queryString);
		return "/BsbFirm/edit";
	}

	@RequiresPermissions("bsbFirm:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model,
			@RequestParam(value = "queryString", required = false) String queryString,
			@ModelAttribute("bsbFirm") BsbFirm bsbFirm) {
		bsbFirm.setUpdateDate(new Date());
		bsbFirm.setUpdateBy((String)SecurityUtils.getSubject().getPrincipal());
		bsbFirmService.updateBsbFirm(bsbFirm);
		SysOrganization sysOrganization = new SysOrganization();
		sysOrganization.setName(bsbFirm.getName());
		SysOrganizationExample sysOrganizationExample = new SysOrganizationExample();
		Criteria criteria = sysOrganizationExample.createCriteria();
		criteria.andFirmIdEqualTo(bsbFirm.getAccount().longValue());
		sysOrganizationService.updateSysOrganizationByExample(sysOrganization, sysOrganizationExample);
		return redirect+ "?" +queryString;
	}
	
	@RequiresPermissions("bsbFirm:view")
	@RequestMapping(value = "/{account}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("account") Integer account) {
		BsbFirm bsbFirm = bsbFirmService.getBsbFirmByAccount(account);
		String phone = bsbFirmService.getPhoneByFirmId(account);
		Firm firm = new Firm();
		BeanUtils.copyProperties(firm, bsbFirm);
		if(StringUtils.isNotEmpty(phone)){
			firm.setPhone(phone);
		}
		model.addAttribute("bsbFirm", firm);
		return "/BsbFirm/view";
	}
}
